package com.bstek.uflo.form.command;

import java.util.Date;

import org.hibernate.Session;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StringUtils;

import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.model.Form;
import com.bstek.uflo.utils.EnvironmentUtils;
import com.bstek.uflo.utils.IDGenerator;

/**
 * @author Jacky.gao
 * @since 2013年11月6日
 */
public class SaveFormCommand implements Command<Form> {
	private long tableId;
	private String content;
	private String name;
	private String id;
	public SaveFormCommand(long tableId,String content,String name,String id){
		this.tableId=tableId;
		this.content=content;
		this.name=name;
		this.id=id;
	}
	public Form execute(Context context) {
		Form form=new Form();
		form.setCategoryId(EnvironmentUtils.getEnvironment().getCategoryId());
		form.setContent(SerializationUtils.serialize(content));
		form.setName(name);
		form.setTableId(tableId);
		Session session=context.getSession();
		form.setUpdateDate(new Date());
		if(StringUtils.hasText(id)){
			form.setId(Long.valueOf(id));
			session.update(form);			
		}else{
			form.setCreateDate(new Date());
			form.setId(IDGenerator.getInstance().nextId());			
			session.save(form);			
		}
		return form;
	}
}
